var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var queryurl = config.BASEPATH+'buy/report/pageEnterDetailReport';
var _height = $(parent).height()-180,_width = $(parent).width()-32;
var api = frameElement.api, W = api.opener;

var handle = {
	operFmatter : function(val, opt, row){
		if(val == "合计"){
			return val;
		}
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-list" title="明细">&#xe64f;</i>';
		html_con += '</div>';
		return html_con;
	}
	
};
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		dateRedioClick("theDate");
		this.initParams();
		Public.buildSeasonCombo("span_pd_season", "pd_season");
		Public.buildYearCombo("span_pd_year", "pd_year");
	},
	initParams:function(){
		var params = api.data;
		$("#begindate").val($.trim(params.begindate));
		$("#enddate").val($.trim(params.enddate));
		$("#supply_name").val($.trim(params.supply_name));
		$("#et_supply_code").val($.trim(params.et_supply_code));
		$("#depot_name").val($.trim(params.depot_name));
		$("#et_depot_code").val($.trim(params.et_depot_code));
		$("#et_manager").val($.trim(params.et_manager));
		$("#bd_name").val($.trim(params.bd_name));
		$("#bd_code").val($.trim(params.bd_code));
		$("#tp_name").val($.trim(params.tp_name));
		$("#tp_code").val($.trim(params.tp_code));
		$("#pd_season").val($.trim(params.pd_season));
		$("#pd_year").val($.trim(params.pd_year));
		$("#pd_code").val($.trim(params.pd_code));
		$("#pd_name").val($.trim(params.pd_name));
	},
	initGrid:function(){
		var colModel = [
	    	{label:'',name: 'pd_code',index:'pd_code',width:100,hidden:true},
	    	{label:'操作',name:'operate', width: 40, fixed:true, formatter: Public.operImgFmatter, align:'center'},
	    	{label:'商品货号',name: 'pd_no',index:'pd_no',width:100},
	    	{label:'商品名称',name: 'pd_name',index:'pd_name',width:100},	
        	{label:'实际数量',name: 'amount',index:'amount',width:80, align:'right'},	
        	{label:'实际金额',name: 'money',index:'money',width:100, align:'right',formatter: PriceLimit.formatMoney},	
	    	{label:'零售金额',name: 'sell_money',index:'sell_money',width:100, align:'right',formatter: PriceLimit.formatMoney}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'local',
			width: _width/2,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:false,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'pd_no'  //图标ID
			},
			loadComplete: function(data){
		    	$('#grid').footerData('set',{pd_no:"合计"});
		    	var ids = $("#grid").getDataIDs();
				if(ids.length>0){
					$("#grid tr:eq(1)").trigger("click");
				}else{
					THISPAGE.initSizeGrid(null, []);
				}
			},
			loadError: function(xhr, status, error){		
			},
			onCellSelect:function(rowid,iRow,iCol,e){
				var rowData = $('#grid').jqGrid('getRowData', rowid);
				THISPAGE.loadSizeGrid(rowData.pd_code);
			}
	    });
	},
	loadSizeGrid : function(pd_code){
		var params = '';
		params += 'begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&et_supply_code='+$("#et_supply_code").val();
		params += '&et_depot_code='+$("#et_depot_code").val();
		params += '&et_manager='+Public.encodeURI($("#et_manager").val());
		params += '&pd_code='+pd_code;
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'buy/report/loadEnterDetailSizeReport?'+params,
			cache:false,
			dataType:"json",
            success: function (data) {
            	if(undefined != data && data.stat == 200){
                    var sizes = data.data.sizes;
                    var rows = data.data.datas;
                    THISPAGE.initSizeGrid(sizes, rows);
				}else{
					Public.tips({type: 1, content : data.message});
				}
            }
        });
	},
	initSizeGrid:function(columns,rows){
		var colModel = [
	    	{label:'颜色', name: 'cr_name',index: '', width: 100,fixed:true},
	    	{label:'杯型', name: 'br_name',index: '', width: 100,fixed:true},
	    	{name:'cr_code',hidden:true},
	    	{name:'br_code',hidden:true},
	    	{name:'id',hidden:true}
	    ];
		if (columns!=null&&columns.length>0){
			for ( var i = 0; i < columns.length; i++) {
				colModel.push({label:columns[i].sz_name,name: "amountMap."+columns[i].sz_code, index: columns[i].sz_code, width: 60,align:'right'});
			}	
		}
		colModel.push({label:'小计',name:'totalamount',width:60,align:'right'});
		$('#sizeGrid').GridUnload();
		$('#sizeGrid').jqGrid({
			datatype: 'local',
			width: _width/2-10,
			height: _height+30,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			viewrecords: true,
			page: 1, //只有一页
			pgbuttons:false,
			pgtext:false,
			shrinkToFit:false,
            footerrow: true,
            userDataOnFooter: true,
			jsonReader: {
				root: 'rows',
				repeatitems : false,
				id:'id'
			},
			loadComplete: function(data){
				var footData = {};
				if (columns!=null&&columns.length>0){
					for ( var i = 0; i < columns.length; i++) {
						footData["amountMap."+columns[i].sz_code] = $('#sizeGrid').getCol("amountMap."+columns[i].sz_code,false,'sum');
					}	
				}
				footData["totalamount"] = $('#sizeGrid').getCol("totalamount",false,'sum');
				footData["cr_name"] = '合计';
				$("#sizeGrid").footerData('set',footData);
			},
			loadError: function(xhr, status, error){
			}
	    });
		$("#sizeGrid").jqGrid('setGridParam', {datatype : 'local',data : rows}).trigger("reloadGrid");
		
		var hasBra=false;
		for(var i=0;i< rows.length;i++){
			if (!hasBra && $.trim(rows[i].br_code) != ''){
				hasBra=true;
				break;
			}
		}
		if (hasBra) {
			$('#sizeGrid').showCol("br_name");
        }else{
        	$('#sizeGrid').hideCol("br_name");
        }
	},
	buildParams : function(){
		var params = '';
		params += 'begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&et_supply_code='+$("#et_supply_code").val();
		params += '&et_depot_code='+$("#et_depot_code").val();
		params += '&bd_code='+$("#bd_code").val();
		params += '&tp_code='+$("#tp_code").val();
		params += '&pd_season='+$("#pd_season").val();
		params += '&pd_year='+$("#pd_year").val();
		params += '&et_manager='+Public.encodeURI($("#et_manager").val());
		params += '&pd_code='+$("#pd_code").val();
		return params;
	},
	reset:function(){
		$("#pd_code").val("");
		$("#pd_name").val("");
		$("#et_manager").val("");
		$("#supply_name").val("");
		$("#et_supply_code").val("");
		$("#depot_name").val("");
		$("#et_depot_code").val("");
		$("#bd_name").val("");
		$("#bd_code").val("");
		$("#tp_name").val("");
		$("#tp_code").val("");
		THISPAGE.$_date.setValue(0);
		$("#span_pd_season").getCombo().selectByValue("");
		$("#span_pd_year").getCombo().selectByValue("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
		$('#grid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#grid").jqGrid("getRowData", id).pd_code);
        });
	}
}
THISPAGE.init();